package cn.iluwen.airline.Controllers;

import cn.iluwen.airline.Config.CookieUtil;
import cn.iluwen.airline.DTOs.BaseResponse;
import cn.iluwen.airline.DTOs.admin.response.AirportListResponse;
import cn.iluwen.airline.DTOs.user.request.*;
import cn.iluwen.airline.DTOs.user.response.*;
import cn.iluwen.airline.DTOs.userRegistration.request.UserRegisterRequest;
import cn.iluwen.airline.DTOs.userRegistration.response.UserRegisterResponse;
import cn.iluwen.airline.Entities.*;
import cn.iluwen.airline.Services.*;
import cn.iluwen.airline.utils.RequestUtils;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户相关API控制器
 */
@Tag(name = "用户API", description = "用户相关的API接口")
@RestController
@RequestMapping("/api/v1/users")
public class UserController {
    @Autowired
    private UserService userService;
    
    @Autowired
    private UserRegistrationService userRegistrationService;
    
    @Autowired
    private UserFlightService userFlightService;

    @Autowired
    private AirportService airportService;

    @Autowired
    private OrderService orderService;
    
    @Autowired
    private CheckInService checkInService;

    @Autowired
    private FlightService flightService;

    /**
     * 用户注册
     */
    @Operation(summary = "用户注册", description = "创建新用户账号")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "注册成功", 
                    content = @Content(mediaType = "application/json", 
                    schema = @Schema(implementation = BaseResponse.class))),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "409", description = "邮箱已存在")
    })
    @PostMapping("/register")
    public ResponseEntity<BaseResponse<UserRegisterResponse>> register(
            @RequestBody UserRegisterRequest request,
            HttpServletRequest httpRequest) {
        try {
            // 验证确认密码
            if (!request.getPassword().equals(request.getConfirmPassword())) {
                return ResponseEntity.badRequest()
                        .body(BaseResponse.error(400, "两次输入的密码不一致"));
            }
            
            // 获取客户端IP
            String clientIp = RequestUtils.getClientIp(httpRequest);
            
            // 确定注册来源（基于User-Agent或其他HTTP请求头）
            String registrationSource = RequestUtils.determineRegistrationSource(httpRequest);
            
            // 调用注册服务
            UserRegistration registration = userRegistrationService.register(
                    request.getUsername(),
                    request.getEmail(),
                    request.getPassword(),
                    request.getPhone(),
                    request.getRealName(),
                    request.getIdCard(),
                    clientIp,
                    registrationSource);
            
            // 构建响应
            UserRegisterResponse response = new UserRegisterResponse();
            response.setUserId(registration.getRegistrationId());
            response.setUsername(registration.getUsername()); // 使用注册时设置的用户名
            response.setEmail(registration.getEmail());
            response.setPhone(registration.getPhone());
            response.setRealName(registration.getRealName());
            response.setIdCard(registration.getIdCard());
            response.setRegistrationDate(registration.getRegistrationDate());
            response.setRegistrationSource(registration.getRegistrationSource());
            
            return ResponseEntity.ok(BaseResponse.success(response));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(BaseResponse.error(400, e.getMessage()));
        }
    }

    /**
     * 用户登录
     */
    @Operation(summary = "用户登录", description = "用户登录并生成Cookie认证")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "登录成功"),
        @ApiResponse(responseCode = "401", description = "登录失败，邮箱或密码错误")
    })
    @PostMapping("/login")
    public ResponseEntity<BaseResponse<UserLoginResponse>> login(
            @RequestBody UserLoginRequest request,
            HttpServletResponse response) {
        try {
            // 通过username查找user记录
            User user = userService.getUserByUsername(request.getUsername());
            if (user == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "账号不存在"));
            }
            
            // 验证密码
            if (!userService.verifyPassword(user, request.getPassword())) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "密码错误"));
            }
            
            // 设置Cookie，保存注册ID
            CookieUtil.setCookie(response, "userId", user.getUserId(), 24 * 60 * 60); // 24小时过期
            
            // 构建响应
            UserLoginResponse loginResponse = new UserLoginResponse();
            loginResponse.setUserId(user.getUserId());
            loginResponse.setUsername(user.getUsername());
            loginResponse.setEmail(user.getEmail());
            loginResponse.setPhone(user.getPhone());
            loginResponse.setRealName(user.getRealName());
            
            return ResponseEntity.ok(BaseResponse.success(loginResponse));
        } catch (Exception e) {
            return ResponseEntity.status(401)
                    .body(BaseResponse.error(401, e.getMessage()));
        }
    }

    /**
     * 获取用户资料
     */
    @Operation(summary = "获取用户资料", description = "获取当前登录用户的个人资料")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "401", description = "未登录或登录已过期"),
        @ApiResponse(responseCode = "404", description = "用户不存在")
    })
    @GetMapping("/profile")
    public ResponseEntity<BaseResponse<UserProfileResponse>> getProfile(HttpServletRequest request) {
        try {
            // 从请求属性中获取userId（在拦截器中设置）
            String userId = (String) request.getAttribute("userId");
            
            // 获取用户信息
            User user = userService.getUserById(userId);
            if (user == null) {
                return ResponseEntity.status(404)
                        .body(BaseResponse.error(404, "用户不存在"));
            }
            
            // 构建响应
            UserProfileResponse response = new UserProfileResponse();
            response.setUserId(user.getUserId());
            response.setUsername(user.getUsername());
            response.setEmail(user.getEmail());
            response.setPhone(user.getPhone());
            response.setRealName(user.getRealName());
            response.setIdCard(user.getIdCard());
            response.setCreatedAt(user.getCreatedAt());
            response.setUpdatedAt(user.getUpdatedAt());
            
            return ResponseEntity.ok(BaseResponse.success(response));
        } catch (Exception e) {
            return ResponseEntity.status(401)
                    .body(BaseResponse.error(401, e.getMessage()));
        }
    }

    /**
     * 更新用户个人资料
     */
    @Operation(summary = "更新用户个人资料", description = "更新当前登录用户的个人资料，仅限于不敏感信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "更新成功"),
        @ApiResponse(responseCode = "401", description = "未登录或登录已过期"),
        @ApiResponse(responseCode = "404", description = "用户不存在")
    })
    @PutMapping("/profile")
    public ResponseEntity<BaseResponse<UserProfileResponse>> updateProfile(
            HttpServletRequest request,
            @RequestBody UpdateUserProfileRequest profileRequest) {
        try {
            // 从请求属性中获取userId（在拦截器中设置）
            String userId = (String) request.getAttribute("userId");
            
            // 获取原用户信息
            User user = userService.getUserById(userId);
            if (user == null) {
                return ResponseEntity.status(404)
                        .body(BaseResponse.error(404, "用户不存在"));
            }
            
            // 更新用户信息
            user.setPhone(profileRequest.getPhone());
            user.setRealName(profileRequest.getRealName());
            user.setIdCard(profileRequest.getIdCard());
            // 不修改username, email, password等敏感字段
            
            // 保存更新
            user = userService.updateUser(user);
            
            // 构建响应
            UserProfileResponse response = new UserProfileResponse();
            response.setUserId(user.getUserId());
            response.setUsername(user.getUsername());
            response.setEmail(user.getEmail());
            response.setPhone(user.getPhone());
            response.setRealName(user.getRealName());
            response.setIdCard(user.getIdCard());
            response.setCreatedAt(user.getCreatedAt());
            response.setUpdatedAt(user.getUpdatedAt());
            
            return ResponseEntity.ok(BaseResponse.success(response));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(BaseResponse.error(400, e.getMessage()));
        }
    }
    
    /**
     * 更新用户信息
     */
    @Operation(summary = "更新用户信息", description = "更新当前登录用户的所有信息，包括敏感信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "更新成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "401", description = "未登录或登录已过期"),
        @ApiResponse(responseCode = "404", description = "用户不存在")
    })
    @PutMapping("/info")
    public ResponseEntity<BaseResponse<UserProfileResponse>> updateUserInfo(
            HttpServletRequest request,
            @RequestBody UpdateUserInfoRequest infoRequest) {
        try {
            // 从请求属性中获取userId（在拦截器中设置）
            String userId = (String) request.getAttribute("userId");
            
            // 获取原用户信息
            User user = userService.getUserById(userId);
            if (user == null) {
                return ResponseEntity.status(404)
                        .body(BaseResponse.error(404, "用户不存在"));
            }
            
            // 更新用户信息
            if (infoRequest.getUsername() != null && !infoRequest.getUsername().isEmpty()) {
                user.setUsername(infoRequest.getUsername());
            }
            if (infoRequest.getEmail() != null && !infoRequest.getEmail().isEmpty()) {
                user.setEmail(infoRequest.getEmail());
            }
            if (infoRequest.getPhone() != null) {
                user.setPhone(infoRequest.getPhone());
            }
            if (infoRequest.getRealName() != null) {
                user.setRealName(infoRequest.getRealName());
            }
            if (infoRequest.getIdCard() != null) {
                user.setIdCard(infoRequest.getIdCard());
            }
            
            // 保存更新
            user = userService.updateUser(user);
            
            // 构建响应
            UserProfileResponse response = new UserProfileResponse();
            response.setUserId(user.getUserId());
            response.setUsername(user.getUsername());
            response.setEmail(user.getEmail());
            response.setPhone(user.getPhone());
            response.setRealName(user.getRealName());
            response.setIdCard(user.getIdCard());
            response.setCreatedAt(user.getCreatedAt());
            response.setUpdatedAt(user.getUpdatedAt());
            
            return ResponseEntity.ok(BaseResponse.success(response));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(BaseResponse.error(400, e.getMessage()));
        }
    }

    /**
     * 修改密码
     */
    @Operation(summary = "修改密码", description = "修改当前登录用户的密码")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "修改成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "401", description = "未登录、登录已过期或原密码错误")
    })
    @PostMapping("/change-password")
    public ResponseEntity<BaseResponse<Void>> changePassword(
            HttpServletRequest request,
            @RequestBody ChangePasswordRequest passwordRequest) {
        try {
            // 验证确认密码
            if (!passwordRequest.getNewPassword().equals(passwordRequest.getConfirmNewPassword())) {
                return ResponseEntity.badRequest()
                        .body(BaseResponse.error(400, "两次输入的新密码不一致"));
            }
            
            // 从请求属性中获取userId（在拦截器中设置）
            String userId = (String) request.getAttribute("userId");
            
            // 调用修改密码服务
            userService.changePassword(
                    userId, passwordRequest.getOldPassword(), passwordRequest.getNewPassword());
            
            return ResponseEntity.ok(BaseResponse.success());
        } catch (Exception e) {
            return ResponseEntity.status(401)
                    .body(BaseResponse.error(401, e.getMessage()));
        }
    }
    
    /**
     * 用户登出
     */
    @Operation(summary = "用户登出", description = "退出登录并清除认证Cookie")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "登出成功")
    })
    @PostMapping("/logout")
    public ResponseEntity<BaseResponse<Void>> logout(HttpServletResponse response) {
        // 删除Cookie
        CookieUtil.deleteCookie(response, "userId");
        return ResponseEntity.ok(BaseResponse.success());
    }
    
    /**
     * 搜索航班
     * @param request 搜索请求
     * @return 航班列表
     */
    @Operation(summary = "搜索航班", description = "根据出发城市、到达城市和日期搜索航班")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "搜索成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误")
    })
    @PostMapping("/flights/search")
    public ResponseEntity<?> searchFlights(@RequestBody SearchFlightRequest request) {
        try {
            FlightSearchResponse result = userFlightService.searchFlights(
                    request.getDepartureCity(),
                    request.getArrivalCity(),
                    request.getDepartureDate(),
                    request.getPageNum(),
                    request.getPageSize()
            );
            
            return ResponseEntity.ok(BaseResponse.success(result));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(BaseResponse.error(400, e.getMessage()));
        }
    }
    
    /**
     * 创建订单
     * @param createOrderRequest 创建订单请求
     * @param request 会话
     * @return 订单信息
     */
    @Operation(summary = "创建订单", description = "创建航班订单")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "创建成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "401", description = "用户未登录")
    })
    @PostMapping("/flights/orders")
    public ResponseEntity<?> createOrder(@RequestBody CreateOrderRequest createOrderRequest, HttpServletRequest request) {
        try {
            // 从请求属性中获取userId（在拦截器中设置），如果没有则尝试从Cookie获取
            String userId = (String) request.getAttribute("userId");
            if (userId == null) {
                userId = CookieUtil.getCookieValue(request, "userId");
            }
            if (userId == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "用户未登录"));
            }
            
            OrderResponse orderResponse = orderService.createOrder(userId, createOrderRequest);
            return ResponseEntity.ok(BaseResponse.success(orderResponse));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(BaseResponse.error(400, e.getMessage()));
        }
    }
    
    /**
     * 获取用户订单列表
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @param request 会话
     * @return 订单列表
     */
    @Operation(summary = "获取用户订单列表", description = "获取当前用户的所有订单")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "401", description = "用户未登录")
    })
    @GetMapping("/flights/orders")
    public ResponseEntity<?> getUserOrders(@RequestParam(required = false) Integer pageNum,
                                           @RequestParam(required = false) Integer pageSize,
                                           HttpServletRequest request) {
        try {
            String userId = (String) request.getAttribute("userId");
            if (userId == null) {
                userId = CookieUtil.getCookieValue(request, "userId");
            }
            if (userId == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "用户未登录"));
            }
            PageInfo<OrderResponse> orders = orderService.getUserOrders(userId, pageNum, pageSize);
            return ResponseEntity.ok(BaseResponse.success(orders));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(BaseResponse.error(400, e.getMessage()));
        }
    }
    
    /**
     * 获取订单详情
     * @param orderId 订单ID
     * @param request 会话
     * @return 订单详情
     */
    @Operation(summary = "获取订单详情", description = "获取指定订单的详细信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "401", description = "用户未登录")
    })
    @GetMapping("/flights/orders/{orderId}")
    public ResponseEntity<?> getOrderDetail(@PathVariable String orderId, HttpServletRequest request) {
        try {
            String userId = (String) request.getAttribute("userId");
            if (userId == null) {
                userId = CookieUtil.getCookieValue(request, "userId");
            }
            if (userId == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "用户未登录"));
            }
            OrderResponse orderResponse = orderService.getOrderDetail(userId, orderId);
            return ResponseEntity.ok(BaseResponse.success(orderResponse));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(BaseResponse.error(400, e.getMessage()));
        }
    }
    
    /**
     * 支付订单
     * @param orderId 订单ID
     * @param request 会话
     * @return 更新后的订单
     */
    @Operation(summary = "支付订单", description = "支付指定订单")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "支付成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "401", description = "用户未登录")
    })
    @PostMapping("/flights/orders/{orderId}/pay")
    public ResponseEntity<?> payOrder(@PathVariable String orderId, HttpServletRequest request) {
        try {
            String userId = (String) request.getAttribute("userId");
            if (userId == null) {
                userId = CookieUtil.getCookieValue(request, "userId");
            }
            if (userId == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "用户未登录"));
            }
            OrderResponse orderResponse = orderService.payOrder(userId, orderId);
            return ResponseEntity.ok(BaseResponse.success(orderResponse));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(BaseResponse.error(400, e.getMessage()));
        }
    }
    
    /**
     * 取消订单
     * @param orderId 订单ID
     * @param request 会话
     * @return 更新后的订单
     */
    @Operation(summary = "取消订单", description = "取消指定订单")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "取消成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "401", description = "用户未登录")
    })
    @PostMapping("/flights/orders/{orderId}/cancel")
    public ResponseEntity<?> cancelOrder(@PathVariable String orderId, HttpServletRequest request) {
        try {
            String userId = (String) request.getAttribute("userId");
            if (userId == null) {
                userId = CookieUtil.getCookieValue(request, "userId");
            }
            if (userId == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "用户未登录"));
            }
            OrderResponse orderResponse = orderService.cancelOrder(userId, orderId);
            return ResponseEntity.ok(BaseResponse.success(orderResponse));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(BaseResponse.error(400, e.getMessage()));
        }
    }
    
    /**
     * 获取航班可用座位
     * @param flightId 航班ID
     * @param ticketClass 舱位等级（可选）
     * @param request 会话
     * @return 座位列表
     */
    @Operation(summary = "获取航班可用座位", description = "获取指定航班的可用座位列表")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "401", description = "用户未登录")
    })
    @GetMapping("/flights/{flightId}/seats")
    public ResponseEntity<?> getAvailableSeats(@PathVariable String flightId,
                                               @RequestParam(required = false) String ticketClass,
                                               HttpServletRequest request) {
        try {
            String userId = (String) request.getAttribute("userId");
            if (userId == null) {
                userId = CookieUtil.getCookieValue(request, "userId");
            }
            if (userId == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "用户未登录"));
            }
            List<Seat> seats = checkInService.getAvailableSeats(flightId, ticketClass);
            return ResponseEntity.ok(BaseResponse.success(seats));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(BaseResponse.error(400, e.getMessage()));
        }
    }
    
    /**
     * 值机选座
     * @param request 值机请求
     * @param request 会话
     * @return 更新后的订单
     */
    @Operation(summary = "值机选座", description = "为航班订单选择座位")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "选座成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "401", description = "用户未登录")
    })
    @PostMapping("/flights/check-in")
    public ResponseEntity<?> checkIn(@RequestBody CheckInRequest checkInRequest, HttpServletRequest request) {
        try {
            String userId = (String) request.getAttribute("userId");
            if (userId == null) {
                userId = CookieUtil.getCookieValue(request, "userId");
            }
            if (userId == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "用户未登录"));
            }
            OrderResponse orderResponse = checkInService.checkIn(userId, checkInRequest);
            return ResponseEntity.ok(BaseResponse.success(orderResponse));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(BaseResponse.error(400, e.getMessage()));
        }
    }


    /**
     * 获取机场列表
     */
    @Operation(summary = "获取机场列表", description = "分页获取所有机场")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "401", description = "未授权")
    })
    @GetMapping("/airports")
    public ResponseEntity<BaseResponse<AirportListResponse>> getAirportList(
            HttpServletRequest request,
            @RequestParam(defaultValue = "0") int pageNum,
            @RequestParam(defaultValue = "0") int pageSize,
            @RequestParam(required = false) String airportName,
            @RequestParam(required = false) String city) {
        try {

            // 实现分页查询
            PageInfo<Airport> pageInfo;

            // 根据查询条件选择不同的查询方法
            if (airportName != null && !airportName.isEmpty()) {
                pageInfo = airportService.getAirportsByNameLike(airportName, pageNum, pageSize);
            } else if (city != null && !city.isEmpty()) {
                pageInfo = airportService.getAirportsByCityLike(city, pageNum, pageSize);
            } else {
                pageInfo = airportService.getAirportsWithPaging(pageNum, pageSize);
            }

            // 构建响应
            AirportListResponse response = new AirportListResponse();
            response.setTotal(pageInfo.getTotal());
            response.setPages(pageInfo.getPages());
            response.setPageNum(pageInfo.getPageNum());
            response.setPageSize(pageInfo.getPageSize());

            List<AirportListResponse.AirportItem> items = new ArrayList<>();
            for (Airport airport : pageInfo.getList()) {
                AirportListResponse.AirportItem item = new AirportListResponse.AirportItem();
                item.setAirportId(airport.getAirportId());
                item.setAirportCode(airport.getAirportCode());
                item.setAirportName(airport.getAirportName());
                item.setCity(airport.getCity());

                items.add(item);
            }
            response.setList(items);

            return ResponseEntity.ok(BaseResponse.success(response));
        } catch (Exception e) {
            return ResponseEntity.status(401)
                    .body(BaseResponse.error(401, e.getMessage()));
        }
    }

    /**
     * 根据航班ID获取航班列表项（FlightItem）
     */
    @Operation(summary = "获取航班列表项", description = "根据航班ID获取航班的FlightItem信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "404", description = "航班不存在")
    })
    @GetMapping("/flights/{flightId}/item")
    public ResponseEntity<?> getFlightItemById(@PathVariable String flightId) {
        // 获取航班
        Flight flight = flightService.getFlightById(flightId);
        if (flight == null) {
            return ResponseEntity.status(404)
                    .body(BaseResponse.error(404, "航班不存在"));
        }
        // 获取机场信息
        Airport departureAirport = airportService.getAirportById(flight.getDepartureAirportId());
        Airport arrivalAirport = airportService.getAirportById(flight.getArrivalAirportId());
        // 构建FlightItem
        FlightSearchResponse.FlightItem item = new FlightSearchResponse.FlightItem();
        item.setFlightId(flight.getFlightId());
        item.setFlightNumber(flight.getFlightNumber());
        if (departureAirport != null) {
            item.setDepartureAirportCode(departureAirport.getAirportCode());
            item.setDepartureAirportName(departureAirport.getAirportName());
            item.setDepartureCity(departureAirport.getCity());
        }
        if (arrivalAirport != null) {
            item.setArrivalAirportCode(arrivalAirport.getAirportCode());
            item.setArrivalAirportName(arrivalAirport.getAirportName());
            item.setArrivalCity(arrivalAirport.getCity());
        }
        item.setDepartureTime(flight.getDepartureTime());
        item.setArrivalTime(flight.getArrivalTime());
        item.setEconomyPrice(flight.getEconomyPrice());
        item.setBusinessPrice(flight.getBusinessPrice());
        // 可用座位数
        int availableEconomy = 0;
        int availableBusiness = 0;
        List<Seat> seats = checkInService.getAvailableSeats(flightId, null);
        for (Seat seat : seats) {
            if ("economy".equals(seat.getSeatClass())) availableEconomy++;
            if ("business".equals(seat.getSeatClass())) availableBusiness++;
        }
        item.setAvailableEconomySeats(availableEconomy);
        item.setAvailableBusinessSeats(availableBusiness);
        return ResponseEntity.ok(BaseResponse.success(item));
    }

    /**
     * 用户申请退票
     */
    @Operation(summary = "申请退票", description = "用户对已支付订单发起退票申请")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "申请成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "401", description = "用户未登录")
    })
    @PostMapping("/flights/orders/{orderId}/refund")
    public ResponseEntity<?> applyRefund(@PathVariable String orderId, HttpServletRequest request) {
        try {
            String userId = (String) request.getAttribute("userId");
            if (userId == null) {
                userId = CookieUtil.getCookieValue(request, "userId");
            }
            if (userId == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "用户未登录"));
            }
            orderService.applyRefund(userId, orderId);
            return ResponseEntity.ok(BaseResponse.success());
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(BaseResponse.error(400, e.getMessage()));
        }
    }

    /**
     * 直接退票（无需管理员审核）
     */
    @Operation(summary = "直接退票", description = "用户对已支付订单发起直接退票操作（无需管理员审核）")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "退票成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "401", description = "用户未登录")
    })
    @PostMapping("/flights/orders/{orderId}/direct-refund")
    public ResponseEntity<?> directRefund(@PathVariable String orderId, HttpServletRequest request) {
        try {
            String userId = (String) request.getAttribute("userId");
            if (userId == null) {
                userId = CookieUtil.getCookieValue(request, "userId");
            }
            if (userId == null) {
                return ResponseEntity.status(401)
                        .body(BaseResponse.error(401, "用户未登录"));
            }
            OrderResponse orderResponse = orderService.refundOrder(userId, orderId);
            return ResponseEntity.ok(BaseResponse.success(orderResponse));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(BaseResponse.error(400, e.getMessage()));
        }
    }

    /**
     * 获取当前用户所有待值机航班（已支付未值机）
     */
    @Operation(summary = "获取待值机航班", description = "获取当前用户所有已支付但未值机的航班")
    @GetMapping("/check-in/flights")
    public ResponseEntity<BaseResponse<List<FlightSearchResponse.FlightItem>>> getCheckInFlights(HttpServletRequest request) {
        String userId = (String) request.getAttribute("userId");
        if (userId == null) {
            userId = CookieUtil.getCookieValue(request, "userId");
        }
        if (userId == null) {
            return ResponseEntity.status(401)
                    .body(BaseResponse.error(401, "用户未登录"));
        }
        // 查询所有已支付未值机的订单
        List<Order> orders = orderService.getPaidUnCheckedInOrders(userId);
        List<FlightSearchResponse.FlightItem> flightItems = new ArrayList<>();
        for (Order order : orders) {
            List<OrderDetail> details = orderService.getOrderDetails(order.getOrderId());
            if (details.isEmpty()) continue;
            Flight flight = flightService.getFlightById(details.get(0).getFlightId());
            if (flight == null) continue;
            // 构建FlightItem
            FlightSearchResponse.FlightItem item = new FlightSearchResponse.FlightItem();
            item.setFlightId(flight.getFlightId());
            item.setFlightNumber(flight.getFlightNumber());
            Airport departureAirport = airportService.getAirportById(flight.getDepartureAirportId());
            if (departureAirport != null) {
                item.setDepartureAirportCode(departureAirport.getAirportCode());
                item.setDepartureAirportName(departureAirport.getAirportName());
                item.setDepartureCity(departureAirport.getCity());
            }
            Airport arrivalAirport = airportService.getAirportById(flight.getArrivalAirportId());
            if (arrivalAirport != null) {
                item.setArrivalAirportCode(arrivalAirport.getAirportCode());
                item.setArrivalAirportName(arrivalAirport.getAirportName());
                item.setArrivalCity(arrivalAirport.getCity());
            }
            item.setDepartureTime(flight.getDepartureTime());
            item.setArrivalTime(flight.getArrivalTime());
            item.setEconomyPrice(flight.getEconomyPrice());
            item.setBusinessPrice(flight.getBusinessPrice());
            // 统计可用座位数
            List<Seat> seats = checkInService.getAvailableSeats(flight.getFlightId(), null);
            int availableEconomy = 0, availableBusiness = 0;
            for (Seat seat : seats) {
                if ("economy".equals(seat.getSeatClass())) availableEconomy++;
                if ("business".equals(seat.getSeatClass())) availableBusiness++;
            }
            item.setAvailableEconomySeats(availableEconomy);
            item.setAvailableBusinessSeats(availableBusiness);
            flightItems.add(item);
        }
        return ResponseEntity.ok(BaseResponse.success(flightItems));
    }

    /**
     * 用户发起改签申请
     */
    @Operation(summary = "用户申请改签", description = "用户对已支付订单发起改签申请（只能改签到相同航线的新航班，保留原座位位置）")
    @PostMapping("/flights/orders/{orderId}/reschedule")
    public ResponseEntity<?> rescheduleOrder(@PathVariable String orderId,
                                             @RequestParam String newFlightId,
                                             HttpServletRequest request) {
        try {
            String userId = (String) request.getAttribute("userId");
            if (userId == null) {
                userId = CookieUtil.getCookieValue(request, "userId");
            }
            if (userId == null) {
                return ResponseEntity.status(401).body(BaseResponse.error(401, "用户未登录"));
            }
            
            // 验证新航班与原订单的航线相同（出发地/目的地不变）
            orderService.rescheduleOrder(userId, orderId, newFlightId);
            
            return ResponseEntity.ok(BaseResponse.success("改签申请已提交，等待管理员审核"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(BaseResponse.error(400, e.getMessage()));
        }
    }
}
